﻿using System;
using System.Runtime.CompilerServices;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

namespace Nirvana
{
    [CustomEditor(typeof(AnimatorTimelineBehaviour))]
    public class AnimatorTimelineBehaviourEditor : Editor
    {
        private SerializedProperty timelineEvents;
        private ReorderableList timelineList;

        public override void OnInspectorGUI()
        {
            base.serializedObject.Update();
            GUILayout.Space(EditorGUIUtility.singleLineHeight);
            this.timelineList.DoLayoutList();
            base.serializedObject.ApplyModifiedProperties();
        }

        private void OnEnable()
        {
            if (this.target == null) return;
            this.timelineEvents = serializedObject.FindProperty("timelineEvents");


            this.timelineList = new ReorderableList(serializedObject, this.timelineEvents);
            this.timelineList.drawHeaderCallback = DrawHeader;
            this.timelineList.elementHeight = 3f * EditorGUIUtility.singleLineHeight;
            this.timelineList.drawElementCallback = DrawElementEnter;

        }

        private void DrawHeader(Rect rect)
        {
            GUI.Label(rect, "Enter Actions:");
        }

        private void DrawElementEnter(Rect r, int index, bool isActive, bool isFocused)
        {
            SerializedProperty arrayElementAtIndex = timelineEvents.GetArrayElementAtIndex(index);
            SerializedProperty normalizedTime = arrayElementAtIndex.FindPropertyRelative("normalizedTime");
            SerializedProperty action = arrayElementAtIndex.FindPropertyRelative("action");
            SerializedProperty eventName = action.FindPropertyRelative("eventName");
            SerializedProperty eventParam = action.FindPropertyRelative("eventParam");

            Rect rect = new Rect(r.x, r.y, r.width, EditorGUIUtility.singleLineHeight);
            EditorGUI.PropertyField(rect, normalizedTime, new GUIContent("Normalized Time:"));
            rect.y += EditorGUIUtility.singleLineHeight;
            EditorGUI.PropertyField(rect, eventName, new GUIContent("Event Name:"));
            rect.y += EditorGUIUtility.singleLineHeight;
            EditorGUI.PropertyField(rect, eventParam, new GUIContent("Event Param:"));

        }

    }
}

